﻿using YunxSoft.AfterSchoolClazz.ViewModels;
using Microsoft.Win32;
using System.Diagnostics;
using System.IO;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using AutoUpdaterDotNET;
using MahApps.Metro.Controls.Dialogs;
using Path = System.Windows.Shapes.Path;

namespace YunxSoft.AfterSchoolClazz.Views
{
    /// <summary>
    /// Interaction logic for MainWindow.xaml
    /// </summary>
    public partial class MainWindow
    {
        private readonly MainWindowViewModel viewModel;
        public MainWindow()
        {
            InitializeComponent();
            viewModel = (MainWindowViewModel)DataContext;
        }

        private void Button_Click(object sender, RoutedEventArgs e)
        {
            // 打开文件管理器选择 .xlsx 文件
            OpenFileDialog openFileDialog = new OpenFileDialog
            {
                Filter = "Excel Files|*.xlsx",
                Title = "选择 Excel 文件"
            };

            if (openFileDialog.ShowDialog() == true)
            {
                viewModel.OpenFileSchedule(openFileDialog.FileName);
            }
        }

        private void Button_Click_1(object sender, RoutedEventArgs e)
        {
            // 打开文件管理器选择 .xlsx 文件
            OpenFileDialog openFileDialog = new OpenFileDialog
            {
                Filter = "Excel Files|*.xlsx",
                Title = "选择 Excel 文件"
            };

            if (openFileDialog.ShowDialog() == true)
            {
                viewModel.OpenFileStudentSchedule(openFileDialog.FileName);
            }
        }

        private async void Button_Click_2(object sender, RoutedEventArgs e)
        {
            if (!viewModel.CheckExportSignInSheet())
                return;

            var saveFileDialog = new SaveFileDialog
            {
                FileName = viewModel.SelectedExportType == Converters.ExportType.BySchedule ? "签到表-按课程.xlsx" : "签到表-按教师.xlsx",
                DefaultExt = ".xlsx",      // Default file extension
                Filter = "Excel files (.xlsx)|*.xlsx"  // Filter files by extension
            };

            var result = saveFileDialog.ShowDialog();

            if (result == true)
            {
                var saveFilePath = saveFileDialog.FileName;
                viewModel.ExportSignInSheet(saveFilePath);

                var settings = new MetroDialogSettings() { AffirmativeButtonText = "打开", NegativeButtonText = "不必了", };
                var dialogResult = await this.ShowMessageAsync("提示", "导出成功！是否立即打开文件？", MessageDialogStyle.AffirmativeAndNegative, settings);
                if (dialogResult == MessageDialogResult.Affirmative)
                {
                    OpenExportedFile(saveFilePath);
                }
            }
        }

        private void OpenExportedFile(string filePath)
        {
            try
            {
                //System.Diagnostics.Process.Start("explorer.exe", $"/select,{filePath}");
                System.Diagnostics.Process.Start(new ProcessStartInfo(filePath) { UseShellExecute = true });
            }
            catch (Exception ex)
            {
                MessageBox.Show($"无法打开文件：{ex.Message}", "错误", MessageBoxButton.OK, MessageBoxImage.Error);
            }
        }

        private void Button_Click_3(object sender, RoutedEventArgs e)
        {
            AutoUpdater.Start("https://gitee.com/yuzho/yunxsoft.afterschoolclazz/releases/download/Release/AutoUpdater.xml");
        }

        private async void Button_Click_4(object sender, RoutedEventArgs e)
        {
            var settings = new MetroDialogSettings() { AffirmativeButtonText = "复制", NegativeButtonText = "关闭", };
            MessageDialogResult result = await this.ShowMessageAsync("关于",
                                                                     viewModel.About,
                                                                     MessageDialogStyle.AffirmativeAndNegative,
                                                                     settings);

            if (result == MessageDialogResult.Affirmative)
                Clipboard.SetText(viewModel.About);
        }

        private async void DownloadTemplate_Click(object sender, RoutedEventArgs e)
        {
            var button = sender as Button;
            if (button == null) return;

            var buttonContent = button.Content;
            
            // 从Tag获取模板文件名
            string templateFileName = button.Tag as string;
            if (string.IsNullOrEmpty(templateFileName))
            {
                MessageBox.Show("未指定模板文件名称", "错误", MessageBoxButton.OK, MessageBoxImage.Error);
                return;
            }

            try
            {
                button.IsEnabled = false;
                button.Content = "正在下载...";
        
                string templatePath = System.IO.Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "Template", templateFileName);
        
                if (!File.Exists(templatePath))
                {
                    await this.ShowMessageAsync("错误", "模板文件不存在，请联系管理员！");
                    return;
                }

                var ext = System.IO.Path.GetExtension(templateFileName);
                SaveFileDialog saveFileDialog = new SaveFileDialog
                {
                    FileName = templateFileName,
                    DefaultExt = ext,
                    Filter = $"{ext} 文件 (*{ext})|*{ext}"
                };

                if (saveFileDialog.ShowDialog() == true)
                {
                    await Task.Run(() => File.Copy(templatePath, saveFileDialog.FileName, true));
            
                    var settings = new MetroDialogSettings() 
                    { 
                        AffirmativeButtonText = "打开", 
                        NegativeButtonText = "不必了" 
                    };
            
                    var dialogResult = await this.ShowMessageAsync("提示", "模板下载成功！是否立即打开文件？", 
                        MessageDialogStyle.AffirmativeAndNegative, settings);
                
                    if (dialogResult == MessageDialogResult.Affirmative)
                    {
                        OpenExportedFile(saveFileDialog.FileName);
                    }
                }
            }
            catch (Exception ex)
            {
                await this.ShowMessageAsync("错误", $"下载模板时出错: {ex.Message}");
            }
            finally
            {
                button.IsEnabled = true;
                button.Content = buttonContent;
            }
        }
    }
}